import { useState, useEffect, useContext } from 'react';
import { NavBar, Button, List, Switch, Toast } from "antd-mobile";
import { AddCircleOutline } from 'antd-mobile-icons';
import { useHistory, useRouteMatch } from "react-router-dom";

import AvatarImage from '../../../components/AvatarImage';
import GroupMemberSelectContactor from '../../../components/GroupMembersSelectContactor';

import { MySdkStoreContext } from '../../../context';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const { mockConfig: { userId: myUserId } } = mySdkStore;
  const { params: { cid } } = useRouteMatch();
  const [silenceMemebers, setSilenceMemebers] = useState([]);
  const [conversationDetail, setConversationDetail] = useState({});
  const [groupMemberSelectContactorProp, setGroupMemberSelectContactorProp] = useState({visible: false, getListApi: '', onOk: () => {}, onClose: () => {}});

  // 获当前会话信息
  const querySingleConversation = async () => {
    const info = await mySdkStore.sdk.querySingleConversation({ cid });
    setConversationDetail(info);
    if (!info.silenceAll) {
      getSlienceMember();
    }
  }

  // 获取被禁言的群成员
  const getSlienceMember = async () => {
    const { rows } = await mySdkStore.sdk.listGroupMembers({ cid, pageIndex: 1, pageSize: 200 });
    setSilenceMemebers(rows.filter(item => item.silence === true));
  }

  useEffect(() => {
    querySingleConversation();
  }, []);

  // 禁言群成员
  const handleAdd = async (userIds) => {
    try {
      const members = userIds.map(({ userId }) => userId);
      await mySdkStore.sdk.updateGroup({ cid, updateType: 'silence_member', group: { userIds: members } });
      setGroupMemberSelectContactorProp({ visible: false});
      getSlienceMember();
    } catch(e: any) {
      Toast.show(e.errorMessage);
    }
  }

  // 点击“添加禁言成员”事件，展示“选择禁言成员”界面
  const handleAddVisible = async () => {
    const silenceMemeberUserIds = silenceMemebers.map(item => item.userId);
    setGroupMemberSelectContactorProp({
      visible: true,
      title: '添加禁言成员',
      cid,
      getListApi: 'listGroupMembers',
      listFilterFunc: (list) => list.filter(item => item !== myUserId && !silenceMemeberUserIds.includes(item.userId)),
      onOk: handleAdd,
      onClose: () => setGroupMemberSelectContactorProp({ visible: false})
    });
  }

  // 解除群成员的禁言
  const handleRemove = async (userId) => {
    try {
      await mySdkStore.sdk.updateGroup({ cid, updateType: 'break_silence_member', group: { userIds: [userId] } });
      Toast.show('禁言已解除');
      getSlienceMember();
    } catch(e: any) {
      Toast.show(e.errorMessage);
    }
  };

  // 处理“全员禁言”的开关
  const handleSwitch = async (checked) => {
    try {
      await mySdkStore.sdk.updateGroup({ cid, updateType: 'silence_flag', group: { silenceAll: checked } });
      querySingleConversation();
      if (checked) {
        setSilenceMemebers([]);
      }
    } catch(e: any) {
      Toast.show(e.errorMessage);
    }
  }

  return (<div className="groupPermissionMutePage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>设置群内禁言</NavBar>
      <List style={{ marginTop: 12, '--border-inner': 0 }}>
        {silenceMemebers.map(item => {
          return <List.Item
            key={item.userId}
            extra={<Button style={{ '--background-color': 'rgba(0,34,60,.2)', '--text-color': 'rgba(0,0,0,0.65)' }} size="small" onClick={() => handleRemove(item.userId)}>移除</Button>}
            prefix={<AvatarImage
            src={item.avatarUrl}
            nickName={item?.nickName}
            userName={item?.userName}
            userId={item?.userId}
            style={{ borderRadius: 8 }}
            fit='cover'
            width={40}
            height={40}
          />}>{item.nickName || item.userName || item.userId}</List.Item>
        })}
      </List>
      <div className={`btnBar${conversationDetail?.silenceAll ? ' disabled' : ''}`} onClick={conversationDetail?.silenceAll ? null : handleAddVisible}>
        <a>
          <AddCircleOutline style={{ marginRight: 14 }} />
          添加禁言成员
        </a>
      </div>
      <List style={{ '--border-top': '0', '--border-bottom': '0', marginTop: 12 }}>
        <List.Item extra={<Switch disabled={myUserId !== conversationDetail.ownerId} checked={conversationDetail?.silenceAll} onChange={checked => handleSwitch(checked)} />}>全员禁言</List.Item>
      </List>
      <div className="tipBar">
        开启后，只允许群主、群管理员发言
      </div>
      { groupMemberSelectContactorProp.visible && <GroupMemberSelectContactor {...groupMemberSelectContactorProp} /> }
    </div>
  )
}